Getting to PnP Framework logs
Table of Contents
Introduction
If you’re anything like me, you’ve been using PnP Framework for provisioning basically forever, and everything has been awesome!
Normally this approach has been great, and whenever there’s been an issue I would debug locally, and keep an eye on the output in Visual Studio
And that worked great, however recently I’ve had more and more fails in production, due to my Azure functions timing out.
Not great, and really hard to reproduce locally, I could spin up Dev Proxy - but since it’s not a matter of my code failing, but rather just randomly taking waaay longer than normally, it’s not really helping me.
Time to look at the logs!
Why logging?
Well, logging is the first step to understanding what’s going on, and what’s suddenly taking so long.
So let’s take a look at how we can get access to the logs from PnP Framework.
Logging in PnP Framework
PnP Framework unfortunately doesn’t have a very intuitive way of enabling logging, since unfortunately it uses TraceLogging, which is a bit of a pain to get to work with, but it had to be possible.
My first stop was PnP.PowerShell, where the awesome folks had already implemented a way to enable logging, and it was just a matter of copying that code:
ConsoleTraceListener consoleListener = new ConsoleTraceListener(false);
consoleListener.Name = ConsoleListenername;
Trace.Listeners.Add(consoleListener);
Or so I thought, turns out the approach PnP.PowerShell uses only allows to log to the console, or a file, and I wanted to log to Application Insights.
Damn, this didn’t give a lot to go off of, but after a bit more back and forth, I managed to get it working, by making my own trace listener:
public class LoggerTraceListener : TraceListener {
private readonly Microsoft.Extensions.Logging.ILogger _logger;
public LoggerTraceListener(Microsoft.Extensions.Logging.ILogger logger) {
_logger = logger;
}
public override void Write(string message) {
_logger.LogInformation(message);
}
public override void WriteLine(string message) {
_logger.LogInformation(message);
}
}
Then from there, using just two lines I could start to get logs in Application Insights:
Trace.Listeners.Add(new LoggerTraceListener(logger));
PnP.Framework.Diagnostics.Log.LogLevel = PnP.Framework.Diagnostics.LogLevel.Debug;
And now I could see all the logs in Application Insights, and I now have a much better idea of what’s going on, and why my Azure functions are suddenly taking so long.
TL;DR
Steal the code snippets above, and remember to enable logging before you go to production, it will save you a lot of headaches!